package be.phl.mycinema;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

public class Utils {

	public final static String IP_ADDRESS_NO_PORT = "192.168.1.143";
	public final static String IP_ADDRESS = IP_ADDRESS_NO_PORT + ":8080";
	public final static String WEBSERVICE_ADDRESS = "http://" + IP_ADDRESS + "/MyCinemaWebservice";
	public final static String WEBSERVICE_BASE_ADDRESS = "http://" + IP_ADDRESS + "/MyCinemaWebservice/webresources/REST";
	public final static String TAG = "UTILS";

	public static boolean isNetworkAvailable(ConnectivityManager cm) {

		NetworkInfo networkInfo = cm.getActiveNetworkInfo();

		if (networkInfo != null && networkInfo.isConnected()) {
			return true;
		}
		return false;
	}

	public static String readJsonFromServer(InputStream in) {

		StringBuilder output = new StringBuilder();
		BufferedReader reader = null;

		try {
			reader = new BufferedReader(new InputStreamReader(in));
			String line;
			
			while ((line = reader.readLine()) != null) {
				output.append(line);
			}
		} catch (IOException e) {
			Log.e(TAG, e.getMessage());
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					Log.e(TAG, e.getMessage());
				}
			}
		}
		
		return output.toString();
	}

	public static Boolean isWebserviceAvailable() {

		Boolean result = false;
		FutureTask<Boolean> task = new FutureTask<Boolean>(new wsAvailable());
		ExecutorService es = Executors.newSingleThreadExecutor();
		es.submit(task);

		try {
			result = (Boolean) task.get();
		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
		}
		
		es.shutdown();
		return result;
	}

	static public class wsAvailable implements Callable<Boolean> {

		public Boolean call() {
			URL url;
			HttpURLConnection urlc = null;
			try {
				url = new URL(WEBSERVICE_ADDRESS);
				urlc = (HttpURLConnection) url.openConnection();
				urlc.setRequestProperty("Connection", "close");
				urlc.setConnectTimeout(5000); // Timeout 5 seconds.
				urlc.connect();

				if (urlc.getResponseCode() == 200) // Success!
				{
					return true;
				} else {
					Log.d("GEEN WEBSERV", "Geen webservice bereikt");
					return false;
				}
			} catch (Exception e) {
				Log.e(TAG, e.getMessage());
				e.printStackTrace();
				return false;
			} finally {
				if (urlc != null) {
					urlc.disconnect();
				}
			}
		}
	}
}